<template>
  <div class="tables-management">
    <!-- 页面标题 -->
    <div class="page-header">
     <div>
      <h2 class="page-title">
        <el-icon><Grid /></el-icon>
        表结构管理
      </h2>

      <p class="page-description">
  当前区域：{{ route.query.region }}<br/>
  当前类别：{{ route.query.type }}
</p>

     </div>

      <div>
          <!-- 返回编辑页卡片 -->
          <div class="back-card" @click="goBackToEditPage">
            <el-icon class="back-icon"><ArrowLeft /></el-icon>
            <span class="back-text">返回分类页</span>
          </div>
      </div>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="showCreateTable = true">
        <el-icon><Plus /></el-icon>
        创建新表
      </el-button>
      <el-button @click="refreshTables">
        <el-icon><Refresh /></el-icon>
        刷新列表
      </el-button>
    </div>

    <!-- 表格列表 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span class="card-title">
              <el-icon><Memo /></el-icon>
              数据表列表 ({{ tables.length }} 个表)
            </span>
          </template>
          
          <el-table :data="tables" style="width: 100%" v-loading="loading">
            <el-table-column prop="name" label="表名" min-width="200">
              <template #default="{ row }">
                <div class="table-name">
                  <el-icon><Grid /></el-icon>
                  <!-- <span>{{ row.name }}</span> -->
                  <span>{{ row.displayName }}</span>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column prop="comment" label="说明" min-width="200">
              <template #default="{ row }">
                <span class="table-comment">{{ row.comment || '无说明' }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="rowCount" label="记录数" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getCountTagType(row.rowCount)">
                  {{ row.rowCount }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column label="列数" width="80" align="center">
              <template #default="{ row }">
                {{ row.columns.length -3}}
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="300" align="center">
              <template #default="{ row }">
                <el-button size="small" @click="viewTableStructure(row)">
                  <el-icon><View /></el-icon>
                  查看结构
                </el-button>
                <el-button type="primary" size="small" @click="manageData(row.name)">
                  <el-icon><Document /></el-icon>
                  管理数据
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="confirmDeleteTable(row.name)"
                  :disabled="isSystemTable(row.name)"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 创建表对话框 -->
    <CreateTable 
      v-model:visible="showCreateTable" 
      @success="handleCreateSuccess"
    />


    <!-- 注意 -->
    <!-- 表结构查看对话框 -->
    <el-dialog
      v-model="showStructureDialog"
      @closed="handleStructureDialogClosed"
      :title="`表结构管理 - ${thirdNameOfCurrent}`"
      width="80%"
      :close-on-click-modal="false"
    >
      <div v-if="currentTable">
        <!-- 表基本信息 -->
        <el-descriptions :column="2" border class="table-info">
          <!-- 测试用：这里是全级表名，勿删 -->
          <!-- <el-descriptions-item label="表名">{{ currentTable.name }}</el-descriptions-item> -->
          <el-descriptions-item label="表名">{{ thirdNameOfCurrent }}</el-descriptions-item>
          <!-- <el-descriptions-item label="表名">{{ thirdName }}</el-descriptions-item> -->
          <!-- <el-descriptions-item label="说明">{{ currentTable.comment || '无说明' }}</el-descriptions-item> -->
          <!-- <el-descriptions-item label="表名">
            <el-input
              v-model="editableTableName"
              placeholder="请输入新的表名"
              size="small"
            />
          </el-descriptions-item> -->
          <el-descriptions-item label="说明">
            <el-input
              v-model="editableComment"
              placeholder="请输入说明"
              size="small"
            />
          </el-descriptions-item>
          <el-descriptions-item label="列数">{{ currentTable.columns.length-3 }}</el-descriptions-item>
          <el-descriptions-item label="记录数">{{ currentTable.rowCount }}</el-descriptions-item>
        </el-descriptions>
        <!-- 添加保存按钮 -->
        <div style="margin-top: 16px; text-align: right;">
          <el-button type="primary" @click="updateTableInfo">保存修改</el-button>
        </div>
        <!-- 注意结束 -->

        <!-- 列信息 -->
        <h4 style="margin-top: 20px;">列信息</h4>
        <!-- //关闭列信息时，重新加载表列表以获取最新数据 -->
        <!-- <el-table :data="currentTable.columns" :key="currentTable.name + '-' + currentTable.columns.length" style="width: 100%"> -->
       <!-- 在 el-table 的 :data 上过滤 'id','所属区域','表类型'这3列，不渲染-->
        <el-table 
        :data="currentTable.columns.filter(col => !['id','所属区域','表类型'].includes(col.Field))" 
        :key="currentTable.name + '-' + currentTable.columns.length" 
        style="width: 100%"
        >
          <el-table-column prop="Field" label="列名" min-width="200"/>
          <!-- 中英文数字类型字典映射 -->
          <!-- <el-table-column prop="Type" label="数据类型" min-width="120" /> -->
           <el-table-column 
            prop="Type" 
            label="数据类型" 
            min-width="150"
            :formatter="formatType"
          />

          <el-table-column prop="Null" label="允许空值" min-width="200" align="center">
            <template #default="{ row }">
              <el-tag :type="row.Null === 'YES' ? 'success' : 'danger'">
                {{ row.Null === 'YES' ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <!-- //隐藏键列，用户友好 -->
          <!-- <el-table-column prop="Key" label="键" width="80" align="center">
            <template #default="{ row }">
              <el-tag v-if="row.Key === 'PRI'" type="danger">主键</el-tag>
              <el-tag v-else-if="row.Key === 'UNI'" type="warning">唯一</el-tag>
              <el-tag v-else-if="row.Key === 'MUL'" type="info">索引</el-tag>
            </template>
          </el-table-column> -->
          <el-table-column prop="Default" label="默认值" min-width="200">
            <template #default="{ row }">
              <span>{{ row.Default || '-' }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="Extra" label="额外信息" min-width="120" /> -->
          <el-table-column label="操作" min-width="200" align="center">
            <template #default="{ row }">
              <el-button 
                type="danger" 
                size="small" 
                @click="confirmDeleteColumn(currentTable.name, row.Field)"
                :disabled="isFrozenColumn(row.Field) || isSystemTable(currentTable.name)"
              >
                删除列
              </el-button>

            </template>
          </el-table-column>
        </el-table>


        <!-- 添加列按钮 -->
        <div style="margin-top: 16px;" v-if="!isSystemTable(currentTable.name)">
          <el-button type="primary" @click="showAddColumn = true">
            <el-icon><Plus /></el-icon>
            添加列
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 添加列对话框 -->
    <el-dialog
      v-model="showAddColumn"
      title="添加新列"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="columnFormRef" :model="columnForm" :rules="columnRules" label-width="100px">
        <el-form-item label="列名" prop="columnName">
          <el-input v-model="columnForm.columnName" placeholder="请输入列名" />
        </el-form-item>
        
        <el-form-item label="数据类型" prop="columnType">
          <el-select v-model="columnForm.columnType" placeholder="请选择数据类型" style="width: 100%">
            <el-option-group
              v-for="group in groupedDataTypes"
              :key="group.category"
              :label="group.category"
            >
              <!-- <el-option
                v-for="type in group.types"
                :key="type.type"
                :label="`${type.type} - ${type.description}`"
                :value="type.type"
              /> -->
              <!-- label 显示从 "英文TYPE + 描述" → 只显示中文描述 -->
               <el-option
                  v-for="type in group.types"
                  :key="type.type"
                  :label="type.description"
                  :value="type.type"
                />
            </el-option-group>
          </el-select>
        </el-form-item>
        
        <!-- <el-form-item 
          label="长度" 
          v-if="selectedDataType?.needsLength"
        > -->
        <el-form-item 
          label="选项" 
          v-if="columnForm.columnType === 'ENUM'"
        >
          <el-input 
            v-model="columnForm.length" 
            placeholder="请输入下拉选项，例：'男','女','未知'（符号为英文）"
          />
        </el-form-item>

          <!-- <el-input 
            v-model="columnForm.length" 
            :placeholder="selectedDataType?.example || '请输入长度'"
          /> -->
        <!-- </el-form-item> -->
        
        <el-form-item label="选项">
          <el-checkbox v-model="columnForm.notNull">不允许空值</el-checkbox>
        </el-form-item>
        
        <el-form-item label="默认值">
          <el-input v-model="columnForm.defaultValue" placeholder="可选，留空表示无默认值" />
        </el-form-item>
        
        <el-form-item label="说明">
          <el-input v-model="columnForm.comment" placeholder="列的说明信息" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAddColumn = false">取消</el-button>
        <el-button type="primary" @click="addColumn" :loading="columnLoading">确定添加</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
// import { useRouter } from 'vue-router'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Grid, Plus, Refresh, Memo, View, Document, Delete 
} from '@element-plus/icons-vue'
import { apiService } from '../api'
import CreateTable from '../components/CreateTable.vue'

const router = useRouter()
const route = useRoute()
// const router = useRouter()
const loading = ref(false)
const columnLoading = ref(false)
const showCreateTable = ref(false)
const showStructureDialog = ref(false)
const showAddColumn = ref(false)

const tables = ref([])
const currentTable = ref(null)
const dataTypes = ref([])

const editableTableName = ref('')
const editableComment = ref('')

// <!-- 中英文数字类型字典映射 -->
const typeNameMap = {
  'BIGINT': '数字（无小数）',
  'DECIMAL': '数字（带小数）',
  'VARCHAR': '文本',
  'TEXT': '长文本',
  'DATETIME': '日期时间'
}
const formatType = (row) => {
  // row.Type = "VARCHAR(255)" 先取前面单词
  const realType = row.Type.split('(')[0].toUpperCase()
  return typeNameMap[realType] || row.Type
}

//弹窗顶部third三级表的过滤
const thirdNameOfCurrent = computed(() => {
  if (!currentTable.value?.name) return ''
  const arr = currentTable.value.name.split('_')
  return arr[arr.length - 1]
})

//冻结这3个自增列不能删除
const isFrozenColumn = (field) => {
  return ['id', '所属区域', '表类型'].includes(field)
}

// 表单数据
const columnForm = reactive({
  columnName: '',
  columnType: '',
  length: '',
  notNull: false,
  defaultValue: '',
  comment: ''
})

const columnFormRef = ref()

// 表单验证规则
const columnRules = {
  columnName: [
    { required: true, message: '请输入列名', trigger: 'blur' }
  ],
  columnType: [
    { required: true, message: '请选择数据类型', trigger: 'change' }
  ]
}


// 系统表判断
const systemTables = ['users', '操作日志']
const isSystemTable = (tableName) => systemTables.includes(tableName)

// 按类别分组的数据类型
const groupedDataTypes = computed(() => {
  const groups = {}
  dataTypes.value.forEach(type => {
    if (!groups[type.category]) {
      groups[type.category] = []
    }
    groups[type.category].push(type)
  })
  
  return Object.entries(groups).map(([category, types]) => ({
    category,
    types
  }))
})

// 当前选择的数据类型
const selectedDataType = computed(() => {
  return dataTypes.value.find(type => type.type === columnForm.columnType)
})

// 获取记录数标签类型
const getCountTagType = (count) => {
  if (count === 0) return 'info'
  if (count < 10) return 'warning'
  if (count < 100) return 'success'
  return 'primary'
}

// 加载表列表
// import { useRoute } from 'vue-router'
// const route = useRoute()

const loadTables = async () => {
  loading.value = true
  try {
    const data = await apiService.getTables()

    // 获取 query 参数
    const region = route.query.region
    const type = route.query.type

    console.log('当前区域:', region)
    console.log('当前类别:', type)

    // 按类别过滤表名
    const filterMap = {
      建筑类: ['建筑', '房屋', '构筑物'],
      人员类: ['人员', '住户', '人口'],
      设备类: ['设备', '设施']
    }

    const keywords = filterMap[type] || []
    const allTables = data.tables || []

    // 模糊匹配表名包含关键词，同时匹配当前 region 和 type
    tables.value = allTables.filter(table =>
      table.name.startsWith(`${region}_${type}_`) // 精确匹配“测试村_建筑类_”
    )


    //在展示前，提取第三级表名,比如存储的是“测试村_建筑类_居民表”，展示的是“居民表”
    tables.value = tables.value.map(table => ({
      ...table,
      displayName: table.name.split('_').pop() // 取最后一个下划线后的部分
    }))

    ElMessage.success(`加载 ${type || '全部'} 类表成功`)
  } catch (error) {
    console.error('加载表列表失败:', error)
    ElMessage.error('加载表列表失败')
  } finally {
    loading.value = false
  }
}


// 加载数据类型
const loadDataTypes = async () => {
  try {
    const data = await apiService.getDataTypes()
    dataTypes.value = data.dataTypes || []
  } catch (error) {
    console.error('加载数据类型失败:', error)
  }
}

// 刷新表列表
const refreshTables = () => {
  loadTables()
}


const viewTableStructure = (table) => {
  // 复制一份列数组，避免原数据顺序污染
  const sortedColumns = [...table.columns]

  // 想固定在最前的字段
  const fixedOrder = ['id', '所属区域', '表类型']

  // 排序逻辑：固定列排在前面，其他的照旧
  sortedColumns.sort((a, b) => {
    const aIndex = fixedOrder.indexOf(a.Field)
    const bIndex = fixedOrder.indexOf(b.Field)
    if (aIndex !== -1 && bIndex !== -1) return aIndex - bIndex
    if (aIndex !== -1) return -1
    if (bIndex !== -1) return 1
    return 0
  })

  // 设置排序后的列
  currentTable.value = { ...table, columns: sortedColumns }

  editableTableName.value = table.name
  editableComment.value = table.comment || ''
  showStructureDialog.value = true
}


// 保存修改
const updateTableInfo = async () => {
  try {
    const oldName = currentTable.value.name
    const newName = editableTableName.value.trim()
    const newComment = editableComment.value.trim()

    if (!newName) {
      ElMessage.warning('表名不能为空')
      return
    }

    // 调用后端接口
    await apiService.updateTableInfo(oldName, newName, newComment)
    ElMessage.success('表信息更新成功')


    // 更新本地数据
    currentTable.value.name = newName
    currentTable.value.comment = newComment

    // 同步表列表
    const index = tables.value.findIndex(t => t.name === oldName)
    if (index !== -1) {
      tables.value[index].name = newName
      tables.value[index].displayName = newName.split('_').pop()//让 UI 重绘成新名字

      tables.value[index].comment = newComment
    }
  } catch (error) {
    console.error('更新表信息失败:', error)
    ElMessage.error('更新表信息失败')
  }
}

// 管理数据
const manageData = (tableName) => {
  router.push({
    path: `/data/${encodeURIComponent(tableName)}`,
    query: {
      region: route.query.region,
      type: route.query.type
    }
  })
}


// 确认删除表
const confirmDeleteTable = (tableName) => {
  ElMessageBox.confirm(
    `确定要删除表 "${tableName}" 吗？此操作将永久删除表及其所有数据，无法恢复！`,
    '警告',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: false
    }
  ).then(async () => {
    try {
      await apiService.deleteTable(tableName)
      ElMessage.success(`表 "${tableName}" 删除成功`)
      loadTables()
    } catch (error) {
      console.error('删除表失败:', error)
      ElMessage.error('删除表失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 确认删除列
const confirmDeleteColumn = (tableName, columnName) => {
  ElMessageBox.confirm(
    `确定要删除表 "${tableName}" 的列 "${columnName}" 吗？此操作将永久删除该列及其数据！`,
    '警告',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await apiService.deleteColumn(tableName, columnName)
      ElMessage.success(`列 "${columnName}" 删除成功`)
      // 重新加载表结构
      const updatedTable = tables.value.find(t => t.name === tableName)
      if (updatedTable) {
        const tableData = await apiService.getTableDetail(tableName)
        updatedTable.columns = tableData.columns
        currentTable.value = updatedTable
      }
    } catch (error) {
      console.error('删除列失败:', error)
      ElMessage.error('删除列失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// // 添加列
// const addColumn = async () => {
//   if (!columnFormRef.value) return
  
//   // 给 varchar 自动补默认长度
//   if (columnForm.columnType === 'ENUM' && !columnForm.length) {
//     columnForm.length = '255'
//   }
//   // 验证表单
//   const valid = await columnFormRef.value.validate().catch(() => false)
//   if (!valid) return
  
//   columnLoading.value = true
//   try {
//     await apiService.addColumn(currentTable.value.name, columnForm)
//     ElMessage.success('列添加成功')
    
//     // 重新加载表结构
//     const tableData = await apiService.getTableDetail(currentTable.value.name)
//     currentTable.value.columns = tableData.columns
    
//     // 更新表列表中的数据
//     const tableIndex = tables.value.findIndex(t => t.name === currentTable.value.name)
//     if (tableIndex !== -1) {
//       tables.value[tableIndex].columns = tableData.columns
//     }
    
//     // 重置表单
//     Object.assign(columnForm, {
//       columnName: '',
//       columnType: '',
//       length: '',
//       notNull: false,
//       defaultValue: '',
//       comment: ''
//     })
    
//     showAddColumn.value = false
//   } catch (error) {
//     console.error('添加列失败:', error)
//     ElMessage.error('添加列失败')
//   } finally {
//     columnLoading.value = false
//   }
// }
// 添加列
const addColumn = async () => {
  if (!columnFormRef.value) return

  // 基本校验
  const valid = await columnFormRef.value.validate().catch(() => false)
  if (!valid) return

  // 业务规则：
  // - VARCHAR 固定使用 255（前端不让改），直接补齐
  // - ENUM 必须填写枚举选项（columnForm.length），否则拒绝提交
  if (columnForm.columnType === 'VARCHAR') {
    columnForm.length = '255'
  } else if (columnForm.columnType === 'ENUM') {
    if (!columnForm.length || !String(columnForm.length).trim()) {
      ElMessage.warning("枚举类型请填写选项，例如：'选项1','选项2'（注意用单引号并用逗号分隔）")
      return
    }
  } else {
    // 其他类型，不需要 length，清空防止误传
    columnForm.length = ''
  }

  columnLoading.value = true
  try {
    await apiService.addColumn(currentTable.value.name, columnForm)
    ElMessage.success('列添加成功')

    // 重新加载表结构
    const tableData = await apiService.getTableDetail(currentTable.value.name)
    currentTable.value.columns = tableData.columns

    // 更新表列表中的数据
    const tableIndex = tables.value.findIndex(t => t.name === currentTable.value.name)
    if (tableIndex !== -1) {
      tables.value[tableIndex].columns = tableData.columns
    }

    // 重置表单
    Object.assign(columnForm, {
      columnName: '',
      columnType: '',
      length: '',
      notNull: false,
      defaultValue: '',
      comment: ''
    })

    showAddColumn.value = false
  } catch (error) {
    console.error('添加列失败:', error)
    ElMessage.error('添加列失败')
  } finally {
    columnLoading.value = false
  }
}

// 创建表成功回调
const handleCreateSuccess = () => {
  loadTables()
  showCreateTable.value = false
}

const goBackToEditPage = () => {
  const region = route.query.region
  if (!region) {
    ElMessage.warning('缺少地区参数，无法返回分类页')
    return
  }
  router.push(`/edit?region=${region}`)
}

const handleStructureDialogClosed = () => {
  // 延迟清空 currentTable，避免 ResizeObserver 报错
  setTimeout(() => {
    currentTable.value = null
  }, 100)
}

// 初始化
onMounted(() => {
  Promise.all([
    loadTables(),
    loadDataTypes()
  ])
})
</script>

<style scoped>
.tables-management {
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  justify-content: flex-end;
}

.page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
  text-align: right; 
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.table-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-comment {
  color: #606266;
  font-style: italic;
}

.table-info {
  margin-bottom: 20px;
}

:deep(.el-descriptions__body) {
  background-color: #fafafa;
}

.back-card {
  display: flex;
  align-items: center;
  cursor: pointer;
  background-color: #f5f7fa;
  border-radius: 12px;
  padding: 8px 16px;
  width: fit-content;
  /* margin-bottom: -10px; */
  margin-top: -50px;
  transition: all 0.2s ease;
  box-shadow: 0 10px 10px rgba(0, 0, 0, 0.08);
}

.back-card:hover {
  background-color: #ecf5ff;
  transform: translateY(-1px);
}

.back-icon {
  margin-right: 8px;
  color: #2687e9;
  font-size: 18px;
}

.back-text {
  font-weight: 500;
  color: #000000;
  font-size: 20px;
}
</style>